
let input = document.getElementById('input');
let lastAns = '';

let figure = function (num) {
    input.value += num;
}

let backSpace = function () {
    let value = input.value;
    if (value) {
        value = value.substring(0, value.length - 1);
        input.value = value;
    }
}

let result = function () {
    let lastResult = operating(input.value);
    lastAns = lastResult + '';
    input.value = lastResult;
}

let empty = function () {
    input.value = "";
}

let ans = function () {
    input.value += lastAns;
}

let operating = function (expresstion) {
    let leftIndex = expresstion.lastIndexOf('(');

    if (leftIndex > -1) {
        let rightIndex = expresstion.lastIndexOf(')');


        if (rightIndex > -1) {
            let result = operating(expresstion.substring(leftIndex + 1, rightIndex));
            return operating(expresstion.substring(0, leftIndex) + ('' + result) + expresstion.substring(rightIndex + 1));
        }
    }

    let sign = expresstion.indexOf('+');
    if (sign > -1) {
        return operating(expresstion.substring(0, sign)) + operating(expresstion.substring(sign + 1));
    }

    sign = expresstion.indexOf('-');
    if (sign > -1) {
        return operating(expresstion.substring(0, sign)) - operating(expresstion.substring(sign + 1));
    }

    sign = expresstion.indexOf('*');
    if (sign > -1) {
        return operating(expresstion.substring(0, sign)) * operating(expresstion.substring(sign + 1));
    }

    sign = expresstion.indexOf('/');
    if (sign > -1) {
        return operating(expresstion.substring(0, sign)) / operating(expresstion.substring(sign + 1));
    }

    sign = expresstion.indexOf('√');
    if (sign > -1) {
        return Math.sqrt(operating(expresstion.substring(sign + 1)));
    }

    sign = expresstion.indexOf('²');
    if (sign > -1) {
        return Math.pow(operating(expresstion.substring(0, sign)), 2);
    }

    sign = expresstion.indexOf('%')
    if (sign > -1) {
        return expresstion.substring(0,sign)/100;
    }

    if (!expresstion) {
        return 0;
    } else return expresstion - 0;
}
